from config import *
from client import *

# ok, i don't want to change this file, so, some new file has been created, 
# then my robot will in my own file, do not change mine!!
class Server(object):
	def run(self):
		self.data = [ [BLANK for i in xrange(SIZE)] for i in xrange(SIZE)]	
		print "==================="

		step_flag = True
		while(1):

			#who's turn to play?
			cur_client = None
			if step_flag == True:
				step_flag = False	
				cur_client = self.black_client
			else:
				step_flag = True
				cur_client = self.white_client
				
			#get chess pos
			raw, col = cur_client.run(self.data)
			"""
			try:
				raw, col = cur_client.run(self.data)
				print raw, col
			except:
				return "program run error!", cur_client.__class__.__name__
			"""
	
			#check if return pos is validate
			if self.in_range(raw, col) and self.data[raw][col] == BLANK:
				self.data[raw][col] = cur_client.chess_var
			else:
				return "progrem return illegal pos", cur_client.__class__.__name__

			#print the chess board	
			self.show_data()

			# judge if game is over?
			if self.is_win():
				return cur_client.__class__.__name__ 
			if self.is_peace():
				return "peace!"

	def show_data(self):
		#show the chess bord
		for i in xrange(SIZE):
			print "  ".join(self.data[i])

		print "\n"


	def is_peace(self):
		#judge if is a peace game
		for i in xrange(SIZE):
			for j in xrange(SIZE):
				if self.data[i][j] == BLANK:
					return False

		return True
		
	def in_range(self, row, col):
		if row >= SIZE or col >= SIZE:
			return False		

		return True
		
	def is_win(self):
		#judge if game has over
		def heng(row, col):
			for i in xrange(WIN_LEN):
				if not self.in_range(row, col + i):
					return False
				
				if self.data[row][col+i] != self.data[row][col]:
					return False
			
			return True

		def shu(row, col):
			for i in xrange(WIN_LEN):
				if not self.in_range(row + i, col):
					return False

				if self.data[row+i][col] != self.data[row][col]:
					return False

			return True

		def pie(row, col):
			for i in xrange(WIN_LEN):
				if not self.in_range(row + i, col - i):
					return False

				if self.data[row + i][col - i] != self.data[row][col]:	
					return False

			return True

		def la(row, col):
			for i in xrange(WIN_LEN):
				if not self.in_range(row + i, col + i):
					return False

				if self.data[row + i][col + i] != self.data[row][col]:
					return False

			return True

		for row in xrange(SIZE):
			for col in xrange(SIZE):
				if self.data[row][col] == BLANK:
					continue

				if heng(row, col) or shu(row, col) or pie(row, col) or la(row, col):
					return True

		return False

def test():
	#test Server()
	server = Server()

	#test is_win()
	for i in xrange(WIN_LEN):
		server.data[0][i] = 1

	assert server.is_win()
		
